package com.liuc.mybatis;

import java.util.List;
import java.util.concurrent.*;

class A implements  Callable<String>{

    private int id;

    public A(int id) {
        this.id = id;
    }

    @Override
    public String call() throws Exception {
        return String.valueOf(id);
    }
}

public class ExecutorDemp {

    public static void main(String[] args) throws  InterruptedException{
       // ExecutorService executor = Executors.newFixedThreadPool(5);//固定线程池
       // ExecutorService executor = Executors.newSingleThreadExecutor();//单例线程池
        //ExecutorService executor = Executors.newCachedThreadPool();//根据业务量而变得线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors()+1,
                3L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy());//默认的
                //new ThreadPoolExecutor.CallerRunsPolicy());//谁掉了我就退还给谁执行
                //new ThreadPoolExecutor.DiscardPolicy());
                new ThreadPoolExecutor.CallerRunsPolicy());
        List<Future<String>>  list = new CopyOnWriteArrayList<>();

            for(int i=1; i<=9; i++){
               // try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
//                threadPool.execute(()->{
//                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
//
//                });
                Future<String> future = threadPool.submit(new A(i));
                list.add(future);
            }
            for (Future<String> future : list) {
                try {
                    System.out.println(future.get());
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } finally {
                    threadPool.shutdown();
                }
            }

    }
}
